/**
 * 视频文件检测工具
 * 用于动态检测和加载视频文件
 */

import type { VideoItem } from '../component/VideoSelector'

// 视频文件扩展名
const VIDEO_EXTENSIONS = ['.mp4', '.webm', '.ogg', '.avi', '.mov', '.wmv', '.flv', '.mkv']

/**
 * 尝试检测 public/videos/ 文件夹中的视频文件
 * 注意：由于浏览器安全限制，无法直接读取文件系统
 * 这里提供一个基于已知文件列表的检测方法
 */
export async function detectVideosInPublicFolder(): Promise<VideoItem[]> {
  const detectedVideos: VideoItem[] = []
  
  // 已知的视频文件列表（基于实际文件夹内容）
  const knownVideoFiles = [
    // 原有视频
    { filename: '视频一.mp4', size: '11MB' },
    { filename: '视频二.mp4', size: '6.1MB' },
    { filename: '视频三.mp4', size: '38MB' },
    
    // 🎬 新添加的 Pexels 视频
    { filename: '4880454-uhd_2160_4096_25fps.mp4', size: '118MB' },
    { filename: '4316251-uhd_2160_3840_30fps.mp4', size: '41MB' },
    { filename: '5362370-uhd_3840_2160_25fps.mp4', size: '17MB' },
    { filename: '3044160-uhd_3840_2160_24fps.mp4', size: '33MB' },
    { filename: '2795750-uhd_3840_2160_25fps.mp4', size: '23MB' },
    { filename: '2795749-uhd_3840_2160_25fps.mp4', size: '20MB' },
    { filename: '2873755-uhd_3840_2160_25fps.mp4', size: '82MB' }
  ]
  
  // 检查每个文件是否存在
  for (const file of knownVideoFiles) {
    try {
      const url = `/videos/${file.filename}`
      const exists = await checkVideoExists(url)
      
      if (exists) {
        const videoItem: VideoItem = {
          id: generateVideoId(file.filename),
          name: getVideoDisplayName(file.filename),
          url,
          size: file.size,
          description: '本地视频文件'
        }
        
        // 尝试获取视频元数据
        try {
          const metadata = await getVideoMetadata(url)
          videoItem.duration = metadata.duration
          videoItem.thumbnail = metadata.thumbnail
        } catch (error) {
          // console.warn(`无法获取视频元数据: ${file.filename}`, error)
        }
        
        detectedVideos.push(videoItem)
      }
    } catch (error) {
      // console.warn(`检测视频文件失败: ${file.filename}`, error)
    }
  }
  
  return detectedVideos
}

/**
 * 检查视频文件是否存在
 */
async function checkVideoExists(url: string): Promise<boolean> {
  try {
    const response = await fetch(url, { method: 'HEAD' })
    return response.ok
  } catch {
    return false
  }
}

/**
 * 获取视频元数据
 */
async function getVideoMetadata(url: string): Promise<{
  duration: string
  thumbnail?: string
}> {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.preload = 'metadata'
    video.src = url
    
    const cleanup = () => {
      video.removeEventListener('loadedmetadata', onLoaded)
      video.removeEventListener('error', onError)
      video.src = ''
    }
    
    const onLoaded = () => {
      const duration = formatDuration(video.duration)
      
      // 生成缩略图
      generateThumbnail(video)
        .then(thumbnail => {
          cleanup()
          resolve({ duration, thumbnail })
        })
        .catch(() => {
          cleanup()
          resolve({ duration })
        })
    }
    
    const onError = () => {
      cleanup()
      reject(new Error('无法加载视频元数据'))
    }
    
    video.addEventListener('loadedmetadata', onLoaded)
    video.addEventListener('error', onError)
    
    // 超时处理
    setTimeout(() => {
      cleanup()
      reject(new Error('获取元数据超时'))
    }, 5000)
  })
}

/**
 * 生成视频缩略图
 */
async function generateThumbnail(video: HTMLVideoElement): Promise<string> {
  return new Promise((resolve, reject) => {
    // 设置到视频的10%位置
    video.currentTime = Math.min(1, video.duration * 0.1)
    
    video.onseeked = () => {
      try {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        
        if (!ctx) {
          reject(new Error('无法创建canvas上下文'))
          return
        }
        
        canvas.width = 160
        canvas.height = 90
        
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        const thumbnail = canvas.toDataURL('image/jpeg', 0.7)
        resolve(thumbnail)
      } catch (error) {
        reject(error)
      }
    }
    
    video.onerror = () => {
      reject(new Error('视频seek失败'))
    }
  })
}

/**
 * 格式化视频时长
 */
function formatDuration(seconds: number): string {
  if (isNaN(seconds) || seconds < 0) return '0:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${minutes}:${secs.toString().padStart(2, '0')}`
  }
}

/**
 * 生成视频ID
 */
function generateVideoId(filename: string): string {
  // 为本地视频生成固定ID，匹配弹幕数据
  const cleanName = filename.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
  
  // 映射到固定的ID，匹配弹幕数据
  const videoMapping: Record<string, string> = {
    // 原有视频
    '视频一': 'local-video-1',
    '视频二': 'local-video-2', 
    '视频三': 'local-video-3',
    'video-1': 'local-video-1',
    'video-2': 'local-video-2',
    'video-3': 'local-video-3',
    
    // 🎬 新添加的 Pexels 视频（现在是本地文件，支持人物检测）
    '4880454-uhd_2160_4096_25fps.mp4': 'pexels-city-night-4k',
    '4316251-uhd_2160_3840_30fps.mp4': 'pexels-nature-landscape-4k',
    '5362370-uhd_3840_2160_25fps.mp4': 'pexels-ocean-waves-4k',
    '3044160-uhd_3840_2160_24fps.mp4': 'pexels-forest-view-4k',
    '2795750-uhd_3840_2160_25fps.mp4': 'pexels-cloud-flow-4k',
    '2795749-uhd_3840_2160_25fps.mp4': 'pexels-mountain-view-4k',
    '2873755-uhd_3840_2160_25fps.mp4': 'pexels-city-building-4k'
  }
  
  // 检查是否有匹配的映射
  for (const [key, id] of Object.entries(videoMapping)) {
    if (cleanName.includes(key.toLowerCase()) || filename.includes(key) || filename === key) {
      return id
    }
  }
  
  // 如果没有匹配，生成默认ID
  return `local-${cleanName}`
}

/**
 * 获取视频显示名称
 */
function getVideoDisplayName(filename: string): string {
  // 特殊处理 Pexels 视频文件名
  const pexelsVideoNames: Record<string, string> = {
    '4880454-uhd_2160_4096_25fps.mp4': '🎬 城市夜景 4K (118MB)',
    '4316251-uhd_2160_3840_30fps.mp4': '🎬 自然风光 4K (41MB)',
    '5362370-uhd_3840_2160_25fps.mp4': '🎬 海洋波浪 4K (17MB)',
    '3044160-uhd_3840_2160_24fps.mp4': '🎬 森林景观 4K (33MB)',
    '2795750-uhd_3840_2160_25fps.mp4': '🎬 云层流动 4K (23MB)',
    '2795749-uhd_3840_2160_25fps.mp4': '🎬 山脉景色 4K (20MB)',
    '2873755-uhd_3840_2160_25fps.mp4': '🎬 城市建筑 4K (82MB)'
  }
  
  // 如果是 Pexels 视频，返回友好名称
  if (pexelsVideoNames[filename]) {
    return pexelsVideoNames[filename]
  }
  
  // 原有视频保持原名
  return filename.replace(/\.[^/.]+$/, '') // 移除扩展名
}

/**
 * 检查文件是否为视频格式
 */
export function isVideoFile(filename: string): boolean {
  const ext = filename.toLowerCase().substring(filename.lastIndexOf('.'))
  return VIDEO_EXTENSIONS.includes(ext)
}

/**
 * 刷新视频列表
 */
export async function refreshVideoList(): Promise<VideoItem[]> {
  // console.log('刷新视频列表...')
  return await detectVideosInPublicFolder()
}
